<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline>
      <el-form-item prop="progressChkType">
        <el-select v-model="queryParams.progressChkType" placeholder="检查类型" style="width: 120px" clearable>
          <el-option v-for="dict in dict.type.cq_progress_chk_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="deptId1">
        <treeselect v-model="queryParams.deptId1" class="tree-select-custom" placeholder="请选择所属部门" no-results-text="暂无数据匹配" no-options-text="暂无数据" :normalizer="normalizerDept" :options="deptOptions" @select="selectDept" />
      </el-form-item>
      <el-form-item prop="projectName">
        <el-input v-model.trim="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" style="width: 160px" />
      </el-form-item>
      <el-form-item prop="rdcType" v-if="hasRandomType">
        <el-select v-model="queryParams.rdcType" placeholder="检查单位" clearable style="width: 100px">
          <el-option v-for="dict in dict.type.cq_random_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="isLockout">
        <el-select v-model="queryParams.isLockout" placeholder="锁定状态" clearable style="width: 100px">
          <el-option v-for="dict in lockStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="-" start-placeholder="检查开始日期" end-placeholder="检查结束日期" style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-download" :loading="exportLoading" @click="handleExport" v-if="showBtns.isExport">导出</el-button>
        <el-button class="btn" type="primary" icon="fa fa-merge" :disabled="selected.length < 2 || loading" :loading="mergeLoading" @click="mergeGldz" v-hasPermi="['cq:gldz:merge']"> 合并计分</el-button>
      </el-form-item>
    </el-form>

    <el-table class="table g-table-tree-expand-align" ref="table" v-loading="loading" :data="constructionList" size="small" row-key="prjchkId" default-expand-all @selection-change="onSelect">
      <el-table-column type="selection" width="50" align="center" :selectable="row => row.level === 1" />
      <el-table-column label="检查类型" min-width="140" class-name="expand-column">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_progress_chk_type" :value="row.progressChkType" />
      </el-table-column>
      <el-table-column label="所属部门" prop="showDeptName" show-overflow-tooltip min-width="200" />
      <el-table-column label="项目" prop="projectName" show-overflow-tooltip min-width="150" />
      <el-table-column label="标段" prop="section" show-overflow-tooltip width="80" />
      <el-table-column label="项目(检查口径)" prop="inpectionCaliber" show-overflow-tooltip width="110" />
      <el-table-column label="施工单位" prop="constructionName" show-overflow-tooltip min-width="200" />
      <el-table-column label="检查单位" align="center" min-width="80">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_random_type" :value="row.rdcType" />
      </el-table-column>
      <el-table-column label="过程分类" align="center" min-width="100">
        <template slot-scope="{ row }">
          <el-tag v-if="row.processType == CHECK_TYPE_CODE.TJGC">土建过程</el-tag>
          <el-tag v-else type="success">精装过程</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="管理动作" align="center" min-width="100">
        <!--<div slot-scope="{ row }" :class="{ disabled: row.isParent }" style="width: 100%">
          <div class="material-item" :class="row.gldzLevel | scoreClass" @click="leakage(row, 'gldz')">{{ row | scoreName('gldz') }}</div>
        </div>-->
        <template slot-scope="{ row }">
          <el-popover placement="top" trigger="hover" v-if="row.scores && row.scores.length">
            <div class="material-tab">
              <div
                class="material-item item-special"
                v-for="sub in row.scores[0].children"
                :key="sub.chkitemId"
                :class="sub.scoreInput | scoreClass"
              >
                <div class="item-cursor" @click="leakage(row, sub)">
                  <div>{{ sub.chkitemName }}</div>
                  <div>{{ sub.scoreInput || '/' }}</div>
                </div>
              </div>
            </div>
            <div slot="reference" class="material-item item-cursor" :class="row.scores[0].scoreInput | scoreClass">{{ row.scores[0].scoreInput || '/' }}</div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="检查人员" align="center" show-overflow-tooltip min-width="100" prop="principalUserName" />
      <el-table-column label="检查时间" align="center" prop="checkDate" width="100" />
      <el-table-column label="锁定状态" align="center" width="80">
        <div slot-scope="{ row }">
          <div @click="toggleIsEnable(row)" style="display: inline-block; cursor: pointer" v-if="row.isEditEnable">
            <i class="el-icon-loading" v-if="!!row.isEnableLoading" />
            <el-switch class="g-switch-in" v-model="row.isLockout" :active-value="1" :inactive-value="0" active-text="锁定" inactive-text="未锁" :width="50" style="pointer-events: none" v-else />
          </div>
          <el-tag size="small" :type="row.isLockout ? 'primary' : 'info'" v-else>{{ row.isLockout ? '锁定' : '未锁' }}</el-tag>
        </div>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding">
        <template slot-scope="{ row }">
          <el-button class="btn" size="mini" type="text" icon="fa fa-split" :disabled="mergeLoading || row.isEnableLoading" :loading="row.splitLoading" @click="splitGldz(row)" v-if="showBtns.split && row.isParent && !row.isLockout"> 拆分</el-button>
          <el-button size="mini" type="text" icon="el-icon-tickets" @click="$refs.GldzDetailRef.init(row)" v-if="showBtns.info && !row.isParent">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" :disabled="previewDisabled(row)" @click="handleReportPreview(row)" v-if="showBtns.preview && row.level === 1 && row.rdcType === 'DEPT1'">预览</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!--防渗漏-->
    <antiseep ref="antiseepRef" :process-type="processType" @submitSuccess="getList" />
    <!-- 详情 -->
    <gldz-detail ref="GldzDetailRef" />
    <gldz-report-preview ref="reportPreviewRef" />
  </div>
</template>
<script>
import { CHECK_TYPE_CODE } from '@/views/checkScore/courseCheck/baseData.js'
// 管理动作列表
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import auth from '@/plugins/auth'
import { CQ_PROGRESS_CHK_TYPE, lockStatusList } from '@/utils/baseData'
import { treeselect } from '@/api/system/dept'
import { unMergeGldz } from '@/api/projectInspection/courseCheck'
import { enableTaskPrjchk, disableTaskPrjchk, exportReportPrjchk } from '@/api/checkScore/cqEval'
import { cqEvalPrjchkPage, mergeGldz } from '@/api/checkScore/courseCheck.js'
import Antiseep from './components/antiseep'
import GldzDetail from './components/GldzDetail'
import GldzReportPreview from './components/GldzReportPreview'
export default {
  name: 'GldzList',
  components: { Treeselect, Antiseep, GldzDetail, GldzReportPreview },
  dicts: ['cq_random_type', 'cq_process_type', 'cq_progress_chk_type'],
  filters: {
    scoreClass(val) {
      if (!val) return ''
      if (val === 'A' || val >= 90) return 'green'
      if (val === 'B' || (val < 90 && val >= 80)) return 'blue'
      if (val === 'C' || val < 80) return 'red'
      return ''
    },
    scoreName(item = {}, key) {
      const level = item[`${key}Level`] || ''
      let score = item[`${key}Score`] || ''
      if (score) {
        const numScore = parseFloat(score)
        if (!isNaN(numScore)) {
          score = Math.round(numScore * 100) / 100
        }
      }
      const val = level ? `${level}${score ? `(${score})` : ''}` : score
      return val || '/'
    }
  },
  data() {
    return {
      CQ_PROGRESS_CHK_TYPE,
      CHECK_TYPE_CODE: CHECK_TYPE_CODE,
      lockStatusList,
      loading: false,
      hasRandomType: false,
      total: 0,
      constructionList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        progressChkType: '',
        deptId1: undefined,
        projectName: '',
        rdcType: '',
        isLockout: ''
      },
      dateRange: [],
      deptOptions: [],
      processType: '',
      selected: [],
      exportLoading: false,
      mergeLoading: false
    }
  },
  computed: {
    showBtns() {
      // 操作按钮权限
      // 详情
      const info = auth.hasPermi('cq:gldz:itemInfo')
      // 预览
      const preview = auth.hasPermi('cq:gldz:preview')
      // 有权解锁(启用)
      const enable = auth.hasPermi('cq:gldz:enable')
      // 有权锁定(禁用)
      const disable = auth.hasPermi('cq:gldz:disable')
      // 导出
      const isExport = auth.hasPermi('cq:gldz:export')
      // 拆分
      const split = auth.hasPermi('cq:gldz:split')
      return { info, preview, enable, disable, isExport, split }
    }
  },
  created() {
    this.getRandoTypePermission()
    treeselect().then(res => (this.deptOptions = res.data))
    this.getList()
  },
  methods: {
    // 判断 检查单位 权限
    getRandoTypePermission() {
      const hasDept1 = auth.hasPermi(`cq:gldz:DEPT1`) // 有集团 权限
      const hasDept2 = auth.hasPermi(`cq:gldz:DEPT2`) // 有集群 权限
      if (hasDept1 && hasDept2) {
        this.queryParams.rdcType = ''
        this.hasRandomType = true
      } else {
        this.hasRandomType = false
        if (hasDept1) {
          this.queryParams.rdcType = 'DEPT1'
        } else if (hasDept2) {
          this.queryParams.rdcType = 'DEPT2'
        } else {
          this.queryParams.rdcType = 'NoList'
        }
      }
    },
    /**
     * 处理报表预览点击
     * @param row
     */
    handleReportPreview(row) {
      this.$refs.reportPreviewRef.init(row)
    },
    previewDisabled(data) {
      return data.gldzScore !== 0 && !data.gldzScore
    },
    normalizerDept(node) {
      // 转换检索部门数据结构
      if (!node.children?.length) delete node.children
      return { id: node.fid, label: node.label, children: node.children }
    },
    selectDept(node) {
      this.queryParams.projectName = ''
    },
    async getList() {
      const { showBtns } = this
      const opt = this.getQuery()
      if (!opt) return

      this.loading = true
      const res = await cqEvalPrjchkPage(opt).catch(() => false)
      this.loading = false
      if (res === false) return

      const data = res.rows || []
      const deptName = i => [i.deptName1, i.deptName2, i.deptName3].filter(i => i).join(' - ')
      const recursion = list =>
        list.map(i => {
          i.showDeptName = deptName(i)
          i.isEnableLoading = false
          i.isEditEnable = i.isLockout ? showBtns.enable : showBtns.disable
          i.splitLoading = false

          // 分数处理
          if (i.scores && i.scores.length) {
            const scores = i.scores
            scores.sort((a, b) => {
              return (a.chkitemCode || '').localeCompare(b.chkitemCode || '')
            })
            scores.forEach(scoreItem => {
              scoreItem.children = []
            })
            const slist = scores.filter(scoreItem => scoreItem.parentId === this.$route.query.chkitemId)
            slist.forEach(scoreItem => {
              for (let i = 0; i < scores.length; i++) {
                if (scoreItem.chkitemId === scores[i].parentId) {
                  scoreItem.children.push({...scores[i]})
                }
              }
            })
            i.scores = slist
          }
          // 无子级时 childList 为 null
          i.children = i.childList || []
          if (!i.children.length) return

          i.isParent = true
          // 父级的锁定状态，用以判断子级得分是否可编辑
          i.children.map(r => (r.isParentEnable = i.isLockout))
          recursion(i.children)
        })
      recursion(data)
      this.constructionList = data
      this.total = res.total || 0
    },
    getQuery() {
      const { dateRange } = this
      const opt = { ...this.queryParams }
      if (Array.isArray(dateRange) && dateRange.length === 2) {
        opt.startTime = dateRange[0]
        opt.endTime = dateRange[1]
      }
      opt.chkitemCode = this.$route.query.chkitemCode
      opt.versionCode = this.$route.query.versionCode
      return opt
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    async handleExport() {
      if (!this.constructionList.length) return this.msgInfo('暂无数据')
      const opt = this.getQuery()
      if (!opt) return
      // 不传分页参数
      delete opt.pageNum
      delete opt.pageSize

      const filename = '管理动作检查表'
      const res1 = await this.$confirm(`确定导出${filename}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      this.exportLoading = true
      const res = await exportReportPrjchk(opt).catch(() => false)
      this.exportLoading = false
      if (res === false) return

      const elink = document.createElement('a')
      elink.download = `${filename}_${new Date().Format('yyyyMMdd')}.xlsx`
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(new Blob([res]))
      elink.click()
    },
    async toggleIsEnable(item) {
      if (item.isEnableLoading || item.splitLoading || this.mergeLoading) return
      const isLockout = item.isLockout ? 0 : 1
      const name = isLockout === 1 ? '锁定' : '解锁'
      const res1 = await this.$confirm(`确认${name}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const opt = { prjchkId: item.prjchkId, isLockout }
      const submitApi = isLockout ? disableTaskPrjchk : enableTaskPrjchk
      item.isEnableLoading = true
      const res = await submitApi(opt).catch(() => false)
      item.isEnableLoading = false
      if (res === false) return

      this.$message.success(`已${name}`)
      this.getList()
    },
    // 防渗漏
    leakage(row, scoreObj) {
      const { isLockout } = row
      // 锁定状态不可点击
      if (row.isParentEnable) return this.$message.info('父级已锁定，无法操作')
      if (isLockout) return this.$message.info('已被锁定，无法操作')
      this.processType = this.$route.query.chkitemCode
      this.$nextTick(() => {
        this.$refs.antiseepRef.show = true
        if (!row.chkitemName) row.chkitemName = '管理动作'
        this.$refs.antiseepRef.init(row, scoreObj)
      })
    },
    onSelect(val) {
      this.selected = val
    },
    async mergeGldz() {
      const { selected } = this
      const projectId = selected[0].projectId
      const rdcType = selected[0].rdcType
      for (const i of selected) {
        if (i.progressChkType === CQ_PROGRESS_CHK_TYPE.SPECIAL_CHK) return this.$message.info('选中项包含专项检查，专项检查不允许合并计分')
        // if (i.isLockout) return this.$message.info('选中项不能包含一级锁定项')
        if (i.projectId !== projectId) return this.$message.info('只能合并相同项目的管理动作')
        if (i.rdcType !== rdcType) return this.$message.info('只能合并相同集群、集团的管理动作')
        if (i.splitLoading) return this.$message.info('选中项包含正在处理拆分的项，请稍后再操作')
        if (i.isEnableLoading) return this.$message.info('选中项包含正在处理锁定状态的项，请稍后再操作')
      }

      const res1 = await this.$confirm(`确定合并选中的${selected.length}项数据？`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const gldzIds = selected.map(i => i.prjchkId).join(',')
      this.mergeLoading = true
      const res = await mergeGldz({ gldzIds, chkitemCode: this.$route.query.chkitemCode }).catch(() => false)
      this.mergeLoading = false
      if (res === false) return

      this.msgSuccess('合并成功')
      this.getList()
    },
    async splitGldz(item) {
      const res1 = await this.$confirm(`确定拆分选中的${item.showDeptName}的项目：${item.projectName}？`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.splitLoading = true
      const res = await unMergeGldz({ gldzIds: item.gldzId }).catch(() => false)
      item.splitLoading = false
      if (res === false) return

      this.msgSuccess('拆分成功')
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.tree-select-custom {
  width: 300px;
  /deep/ {
    .vue-treeselect__control {
      height: 28px;
      font-size: 12px;
    }
    .vue-treeselect__placeholder,
    .vue-treeselect__single-value {
      line-height: 26px;
    }
    .vue-treeselect__input-container,
    .vue-treeselect__input {
      height: 26px;
    }
  }
}
.btn /deep/ .fa {
  font-size: inherit;
}
.table /deep/ {
  .el-checkbox.is-disabled {
    display: none;
  }
  .cell {
    display: flex;
    align-items: center;
  }
}
.material-tab {
  .material-item {
    padding: 6px 10px;
    margin: 0 10px;
  }
}
.item-cursor {
  cursor: pointer;
}
.material-item {
  display: inline-block;
  text-align: center;
  padding: 2px 10px;
  color: #909399;
  border: 1px currentColor dashed;
  border-radius: 4px;
  cursor: pointer;
}
.green {
  color: #67c23a;
}
.blue {
  color: #409eff;
}
.red {
  color: #f56c6c;
}
</style>
